home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / bison / bisn119s.zoo / bison.info-2 < prev    next >
Encoding:
GNU Info File  |  1992-09-05  |  49.7 KB  |  1,386 lines

  1. This is Info file bison.info, produced by Makeinfo-1.47 from the input
  2. file /home/gd/gnu/bison/bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled "GNU General Public License" and "Conditions
  15. for Using Bison" are included exactly as in the original, and provided
  16. that the entire resulting derived work is distributed under the terms
  17. of a permission notice identical to this one.
  18.  
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that the sections entitled "GNU General Public
  22. License", "Conditions for Using Bison" and this permission notice may be
  23. included in translations approved by the Free Software Foundation
  24. instead of in the original English.
  25.  
  26. File: bison.info,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Expr,  Up: RPN Calc
  27.  
  28. The `rpcalc' Lexical Analyzer
  29. -----------------------------
  30.  
  31.    The lexical analyzer's job is low-level parsing: converting
  32. characters or sequences of characters into tokens.  The Bison parser
  33. gets its tokens by calling the lexical analyzer.  *Note Lexical::.
  34.  
  35.    Only a simple lexical analyzer is needed for the RPN calculator. 
  36. This lexical analyzer skips blanks and tabs, then reads in numbers as
  37. `double' and returns them as `NUM' tokens.  Any other character that
  38. isn't part of a number is a separate token.  Note that the token-code
  39. for such a single-character token is the character itself.
  40.  
  41.    The return value of the lexical analyzer function is a numeric code
  42. which represents a token type.  The same text used in Bison rules to
  43. stand for this token type is also a C expression for the numeric code
  44. for the type. This works in two ways.  If the token type is a character
  45. literal, then its numeric code is the ASCII code for that character;
  46. you can use the same character literal in the lexical analyzer to
  47. express the number.  If the token type is an identifier, that
  48. identifier is defined by Bison as a C macro whose definition is the
  49. appropriate number.  In this example, therefore, `NUM' becomes a macro
  50. for `yylex' to use.
  51.  
  52.    The semantic value of the token (if it has one) is stored into the
  53. global variable `yylval', which is where the Bison parser will look for
  54. it. (The C data type of `yylval' is `YYSTYPE', which was defined at the
  55. beginning of the grammar; *note Rpcalc Decls::..)
  56.  
  57.    A token type code of zero is returned if the end-of-file is
  58. encountered. (Bison recognizes any nonpositive value as indicating the
  59. end of the input.)
  60.  
  61.    Here is the code for the lexical analyzer:
  62.  
  63.      /* Lexical analyzer returns a double floating point
  64.         number on the stack and the token NUM, or the ASCII
  65.         character read if not a number.  Skips all blanks
  66.         and tabs, returns 0 for EOF. */
  67.      
  68.      #include <ctype.h>
  69.      
  70.      yylex ()
  71.      {
  72.        int c;
  73.      
  74.        /* skip white space  */
  75.        while ((c = getchar ()) == ' ' || c == '\t')
  76.          ;
  77.        /* process numbers   */
  78.        if (c == '.' || isdigit (c))
  79.          {
  80.            ungetc (c, stdin);
  81.            scanf ("%lf", &yylval);
  82.            return NUM;
  83.          }
  84.        /* return end-of-file  */
  85.        if (c == EOF)
  86.          return 0;
  87.        /* return single chars */
  88.        return c;
  89.      }
  90.  
  91. File: bison.info,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  92.  
  93. The Controlling Function
  94. ------------------------
  95.  
  96.    In keeping with the spirit of this example, the controlling function
  97. is kept to the bare minimum.  The only requirement is that it call
  98. `yyparse' to start the process of parsing.
  99.  
  100.      main ()
  101.      {
  102.        yyparse ();
  103.      }
  104.  
  105. File: bison.info,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  106.  
  107. The Error Reporting Routine
  108. ---------------------------
  109.  
  110.    When `yyparse' detects a syntax error, it calls the error reporting
  111. function `yyerror' to print an error message (usually but not always
  112. `"parse error"').  It is up to the programmer to supply `yyerror'
  113. (*note Interface::.), so here is the definition we will use:
  114.  
  115.      #include <stdio.h>
  116.      
  117.      yyerror (s)  /* Called by yyparse on error */
  118.           char *s;
  119.      {
  120.        printf ("%s\n", s);
  121.      }
  122.  
  123.    After `yyerror' returns, the Bison parser may recover from the error
  124. and continue parsing if the grammar contains a suitable error rule
  125. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  126. have not written any error rules in this example, so any invalid input
  127. will cause the calculator program to exit.  This is not clean behavior
  128. for a real calculator, but it is adequate in the first example.
  129.  
  130. File: bison.info,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  131.  
  132. Running Bison to Make the Parser
  133. --------------------------------
  134.  
  135.    Before running Bison to produce a parser, we need to decide how to
  136. arrange all the source code in one or more source files.  For such a
  137. simple example, the easiest thing is to put everything in one file. 
  138. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  139. "additional C code" section of the file (*note Grammar Layout::.).
  140.  
  141.    For a large project, you would probably have several source files,
  142. and use `make' to arrange to recompile them.
  143.  
  144.    With all the source in a single file, you use the following command
  145. to convert it into a parser file:
  146.  
  147.      bison FILE_NAME.y
  148.  
  149. In this example the file was called `rpcalc.y' (for "Reverse Polish
  150. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  151. the `.y' from the original file name. The file output by Bison contains
  152. the source code for `yyparse'.  The additional functions in the input
  153. file (`yylex', `yyerror' and `main') are copied verbatim to the output.
  154.  
  155. File: bison.info,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  156.  
  157. Compiling the Parser File
  158. -------------------------
  159.  
  160.    Here is how to compile and run the parser file:
  161.  
  162.      # List files in current directory.
  163.      % ls
  164.      rpcalc.tab.c  rpcalc.y
  165.      
  166.      # Compile the Bison parser.
  167.      # `-lm' tells compiler to search math library for `pow'.
  168.      % cc rpcalc.tab.c -lm -o rpcalc
  169.      
  170.      # List files again.
  171.      % ls
  172.      rpcalc  rpcalc.tab.c  rpcalc.y
  173.  
  174.    The file `rpcalc' now contains the executable code.  Here is an
  175. example session using `rpcalc'.
  176.  
  177.      % rpcalc
  178.      4 9 +
  179.      13
  180.      3 7 + 3 4 5 *+-
  181.      -13
  182.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  183.      13
  184.      5 6 / 4 n +
  185.      -3.166666667
  186.      3 4 ^                            Exponentiation
  187.      81
  188.      ^D                               End-of-file indicator
  189.      %
  190.  
  191. File: bison.info,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  192.  
  193. Infix Notation Calculator: `calc'
  194. =================================
  195.  
  196.    We now modify rpcalc to handle infix operators instead of postfix. 
  197. Infix notation involves the concept of operator precedence and the need
  198. for parentheses nested to arbitrary depth.  Here is the Bison code for
  199. `calc.y', an infix desk-top calculator.
  200.  
  201.      /* Infix notation calculator--calc */
  202.      
  203.      %{
  204.      #define YYSTYPE double
  205.      #include <math.h>
  206.      %}
  207.      
  208.      /* BISON Declarations */
  209.      %token NUM
  210.      %left '-' '+'
  211.      %left '*' '/'
  212.      %left NEG     /* negation--unary minus */
  213.      %right '^'    /* exponentiation        */
  214.      
  215.      /* Grammar follows */
  216.      %%
  217.      input:    /* empty string */
  218.              | input line
  219.      ;
  220.      
  221.      line:     '\n'
  222.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  223.      ;
  224.      
  225.      exp:      NUM                { $$ = $1;         }
  226.              | exp '+' exp        { $$ = $1 + $3;    }
  227.              | exp '-' exp        { $$ = $1 - $3;    }
  228.              | exp '*' exp        { $$ = $1 * $3;    }
  229.              | exp '/' exp        { $$ = $1 / $3;    }
  230.              | '-' exp  %prec NEG { $$ = -$2;        }
  231.              | exp '^' exp        { $$ = pow ($1, $3); }
  232.              | '(' exp ')'        { $$ = $2;         }
  233.      ;
  234.      %%
  235.  
  236. The functions `yylex', `yyerror' and `main' can be the same as before.
  237.  
  238.    There are two important new features shown in this code.
  239.  
  240.    In the second section (Bison declarations), `%left' declares token
  241. types and says they are left-associative operators.  The declarations
  242. `%left' and `%right' (right associativity) take the place of `%token'
  243. which is used to declare a token type name without associativity. 
  244. (These tokens are single-character literals, which ordinarily don't
  245. need to be declared.  We declare them here to specify the
  246. associativity.)
  247.  
  248.    Operator precedence is determined by the line ordering of the
  249. declarations; the higher the line number of the declaration (lower on
  250. the page or screen), the higher the precedence.  Hence, exponentiation
  251. has the highest precedence, unary minus (`NEG') is next, followed by
  252. `*' and `/', and so on.  *Note Precedence::.
  253.  
  254.    The other important new feature is the `%prec' in the grammar section
  255. for the unary minus operator.  The `%prec' simply instructs Bison that
  256. the rule `| '-' exp' has the same precedence as `NEG'--in this case the
  257. next-to-highest.  *Note Contextual Precedence::.
  258.  
  259.    Here is a sample run of `calc.y':
  260.  
  261.      % calc
  262.      4 + 4.5 - (34/(8*3+-3))
  263.      6.880952381
  264.      -56 + 2
  265.      -54
  266.      3 ^ 2
  267.      9
  268.  
  269. File: bison.info,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  270.  
  271. Simple Error Recovery
  272. =====================
  273.  
  274.    Up to this point, this manual has not addressed the issue of "error
  275. recovery"--how to continue parsing after the parser detects a syntax
  276. error.  All we have handled is error reporting with `yyerror'.  Recall
  277. that by default `yyparse' returns after calling `yyerror'.  This means
  278. that an erroneous input line causes the calculator program to exit. Now
  279. we show how to rectify this deficiency.
  280.  
  281.    The Bison language itself includes the reserved word `error', which
  282. may be included in the grammar rules.  In the example below it has been
  283. added to one of the alternatives for `line':
  284.  
  285.      line:     '\n'
  286.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  287.              | error '\n' { yyerrok;                  }
  288.      ;
  289.  
  290.    This addition to the grammar allows for simple error recovery in the
  291. event of a parse error.  If an expression that cannot be evaluated is
  292. read, the error will be recognized by the third rule for `line', and
  293. parsing will continue.  (The `yyerror' function is still called upon to
  294. print its message as well.)  The action executes the statement
  295. `yyerrok', a macro defined automatically by Bison; its meaning is that
  296. error recovery is complete (*note Error Recovery::.).  Note the
  297. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  298.  
  299.    This form of error recovery deals with syntax errors.  There are
  300. other kinds of errors; for example, division by zero, which raises an
  301. exception signal that is normally fatal.  A real calculator program
  302. must handle this signal and use `longjmp' to return to `main' and
  303. resume parsing input lines; it would also have to discard the rest of
  304. the current line of input.  We won't discuss this issue further because
  305. it is not specific to Bison programs.
  306.  
  307. File: bison.info,  Node: Multi-function Calc,  Next: Exercises,  Prev: Simple Error Recovery,  Up: Examples
  308.  
  309. Multi-Function Calculator: `mfcalc'
  310. ===================================
  311.  
  312.    Now that the basics of Bison have been discussed, it is time to move
  313. on to a more advanced problem.  The above calculators provided only five
  314. functions, `+', `-', `*', `/' and `^'.  It would be nice to have a
  315. calculator that provides other mathematical functions such as `sin',
  316. `cos', etc.
  317.  
  318.    It is easy to add new operators to the infix calculator as long as
  319. they are only single-character literals.  The lexical analyzer `yylex'
  320. passes back all non-number characters as tokens, so new grammar rules
  321. suffice for adding a new operator.  But we want something more
  322. flexible: built-in functions whose syntax has this form:
  323.  
  324.      FUNCTION_NAME (ARGUMENT)
  325.  
  326. At the same time, we will add memory to the calculator, by allowing you
  327. to create named variables, store values in them, and use them later.
  328. Here is a sample session with the multi-function calculator:
  329.  
  330.      % acalc
  331.      pi = 3.141592653589
  332.      3.1415926536
  333.      sin(pi)
  334.      0.0000000000
  335.      alpha = beta1 = 2.3
  336.      2.3000000000
  337.      alpha
  338.      2.3000000000
  339.      ln(alpha)
  340.      0.8329091229
  341.      exp(ln(beta1))
  342.      2.3000000000
  343.      %
  344.  
  345.    Note that multiple assignment and nested function calls are
  346. permitted.
  347.  
  348. * Menu:
  349.  
  350. * Decl: Mfcalc Decl.     Bison declarations for multi-function calculator.
  351. * Rules: Mfcalc Rules.   Grammar rules for the calculator.
  352. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  353.  
  354. File: bison.info,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Prev: Multi-function Calc,  Up: Multi-function Calc
  355.  
  356. Declarations for `mfcalc'
  357. -------------------------
  358.  
  359.    Here are the C and Bison declarations for the multi-function
  360. calculator.
  361.  
  362.      %{
  363.      #include <math.h>  /* For math functions, cos(), sin(), etc. */
  364.      #include "calc.h"  /* Contains definition of `symrec'        */
  365.      %}
  366.      %union {
  367.      double     val;  /* For returning numbers.                   */
  368.      symrec  *tptr;   /* For returning symbol-table pointers      */
  369.      }
  370.      
  371.      %token <val>  NUM        /* Simple double precision number   */
  372.      %token <tptr> VAR FNCT   /* Variable and Function            */
  373.      %type  <val>  exp
  374.      
  375.      %right '='
  376.      %left '-' '+'
  377.      %left '*' '/'
  378.      %left NEG     /* Negation--unary minus */
  379.      %right '^'    /* Exponentiation        */
  380.      
  381.      /* Grammar follows */
  382.      
  383.      %%
  384.  
  385.    The above grammar introduces only two new features of the Bison
  386. language. These features allow semantic values to have various data
  387. types (*note Multiple Types::.).
  388.  
  389.    The `%union' declaration specifies the entire list of possible types;
  390. this is instead of defining `YYSTYPE'.  The allowable types are now
  391. double-floats (for `exp' and `NUM') and pointers to entries in the
  392. symbol table.  *Note Union Decl::.
  393.  
  394.    Since values can now have various types, it is necessary to
  395. associate a type with each grammar symbol whose semantic value is used.
  396.  These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their declarations
  397. are augmented with information about their data type (placed between
  398. angle brackets).
  399.  
  400.    The Bison construct `%type' is used for declaring nonterminal
  401. symbols, just as `%token' is used for declaring token types.  We have
  402. not used `%type' before because nonterminal symbols are normally
  403. declared implicitly by the rules that define them.  But `exp' must be
  404. declared explicitly so we can specify its value type.  *Note Type
  405. Decl::.
  406.  
  407. File: bison.info,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  408.  
  409. Grammar Rules for `mfcalc'
  410. --------------------------
  411.  
  412.    Here are the grammar rules for the multi-function calculator. Most
  413. of them are copied directly from `calc'; three rules, those which
  414. mention `VAR' or `FNCT', are new.
  415.  
  416.      input:   /* empty */
  417.              | input line
  418.      ;
  419.      
  420.      line:
  421.                '\n'
  422.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  423.              | error '\n' { yyerrok;                  }
  424.      ;
  425.      
  426.      exp:      NUM                { $$ = $1;                         }
  427.              | VAR                { $$ = $1->value.var;              }
  428.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  429.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  430.              | exp '+' exp        { $$ = $1 + $3;                    }
  431.              | exp '-' exp        { $$ = $1 - $3;                    }
  432.              | exp '*' exp        { $$ = $1 * $3;                    }
  433.              | exp '/' exp        { $$ = $1 / $3;                    }
  434.              | '-' exp  %prec NEG { $$ = -$2;                        }
  435.              | exp '^' exp        { $$ = pow ($1, $3);               }
  436.              | '(' exp ')'        { $$ = $2;                         }
  437.      ;
  438.      /* End of grammar */
  439.      %%
  440.  
  441. File: bison.info,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  442.  
  443. The `mfcalc' Symbol Table
  444. -------------------------
  445.  
  446.    The multi-function calculator requires a symbol table to keep track
  447. of the names and meanings of variables and functions.  This doesn't
  448. affect the grammar rules (except for the actions) or the Bison
  449. declarations, but it requires some additional C functions for support.
  450.  
  451.    The symbol table itself consists of a linked list of records.  Its
  452. definition, which is kept in the header `calc.h', is as follows.  It
  453. provides for either functions or variables to be placed in the table.
  454.  
  455.      /* Data type for links in the chain of symbols.      */
  456.      struct symrec
  457.      {
  458.        char *name;  /* name of symbol                     */
  459.        int type;    /* type of symbol: either VAR or FNCT */
  460.        union {
  461.          double var;           /* value of a VAR          */
  462.          double (*fnctptr)();  /* value of a FNCT         */
  463.        } value;
  464.        struct symrec *next;    /* link field              */
  465.      };
  466.      
  467.      typedef struct symrec symrec;
  468.      
  469.      /* The symbol table: a chain of `struct symrec'.     */
  470.      extern symrec *sym_table;
  471.      
  472.      symrec *putsym ();
  473.      symrec *getsym ();
  474.  
  475.    The new version of `main' includes a call to `init_table', a
  476. function that initializes the symbol table.  Here it is, and
  477. `init_table' as well:
  478.  
  479.      #include <stdio.h>
  480.      
  481.      main ()
  482.      {
  483.        init_table ();
  484.        yyparse ();
  485.      }
  486.      
  487.      yyerror (s)  /* Called by yyparse on error */
  488.           char *s;
  489.      {
  490.        printf ("%s\n", s);
  491.      }
  492.      
  493.      struct init
  494.      {
  495.        char *fname;
  496.        double (*fnct)();
  497.      };
  498.      
  499.      struct init arith_fncts[]
  500.        = {
  501.            "sin", sin,
  502.            "cos", cos,
  503.            "atan", atan,
  504.            "ln", log,
  505.            "exp", exp,
  506.            "sqrt", sqrt,
  507.            0, 0
  508.          };
  509.      
  510.      /* The symbol table: a chain of `struct symrec'.  */
  511.      symrec *sym_table = (symrec *)0;
  512.      
  513.      init_table ()  /* puts arithmetic functions in table. */
  514.      {
  515.        int i;
  516.        symrec *ptr;
  517.        for (i = 0; arith_fncts[i].fname != 0; i++)
  518.          {
  519.            ptr = putsym (arith_fncts[i].fname, FNCT);
  520.            ptr->value.fnctptr = arith_fncts[i].fnct;
  521.          }
  522.      }
  523.  
  524.    By simply editing the initialization list and adding the necessary
  525. include files, you can add additional functions to the calculator.
  526.  
  527.    Two important functions allow look-up and installation of symbols in
  528. the symbol table.  The function `putsym' is passed a name and the type
  529. (`VAR' or `FNCT') of the object to be installed.  The object is linked
  530. to the front of the list, and a pointer to the object is returned. The
  531. function `getsym' is passed the name of the symbol to look up.  If
  532. found, a pointer to that symbol is returned; otherwise zero is returned.
  533.  
  534.      symrec *
  535.      putsym (sym_name,sym_type)
  536.           char *sym_name;
  537.           int sym_type;
  538.      {
  539.        symrec *ptr;
  540.        ptr = (symrec *) malloc (sizeof (symrec));
  541.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  542.        strcpy (ptr->name,sym_name);
  543.        ptr->type = sym_type;
  544.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  545.        ptr->next = (struct symrec *)sym_table;
  546.        sym_table = ptr;
  547.        return ptr;
  548.      }
  549.      
  550.      symrec *
  551.      getsym (sym_name)
  552.           char *sym_name;
  553.      {
  554.        symrec *ptr;
  555.        for (ptr = sym_table; ptr != (symrec *) 0;
  556.             ptr = (symrec *)ptr->next)
  557.          if (strcmp (ptr->name,sym_name) == 0)
  558.            return ptr;
  559.        return 0;
  560.      }
  561.  
  562.    The function `yylex' must now recognize variables, numeric values,
  563. and the single-character arithmetic operators.  Strings of alphanumeric
  564. characters with a leading nondigit are recognized as either variables or
  565. functions depending on what the symbol table says about them.
  566.  
  567.    The string is passed to `getsym' for look up in the symbol table.  If
  568. the name appears in the table, a pointer to its location and its type
  569. (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already in
  570. the table, then it is installed as a `VAR' using `putsym'.  Again, a
  571. pointer and its type (which must be `VAR') is returned to `yyparse'.
  572.  
  573.    No change is needed in the handling of numeric values and arithmetic
  574. operators in `yylex'.
  575.  
  576.      #include <ctype.h>
  577.      yylex ()
  578.      {
  579.        int c;
  580.      
  581.        /* Ignore whitespace, get first nonwhite character.  */
  582.        while ((c = getchar ()) == ' ' || c == '\t');
  583.      
  584.        if (c == EOF)
  585.          return 0;
  586.      
  587.        /* Char starts a number => parse the number.         */
  588.        if (c == '.' || isdigit (c))
  589.          {
  590.            ungetc (c, stdin);
  591.            scanf ("%lf", &yylval.val);
  592.            return NUM;
  593.          }
  594.      
  595.        /* Char starts an identifier => read the name.       */
  596.        if (isalpha (c))
  597.          {
  598.            symrec *s;
  599.            static char *symbuf = 0;
  600.            static int length = 0;
  601.            int i;
  602.      
  603.            /* Initially make the buffer long enough
  604.               for a 40-character symbol name.  */
  605.            if (length == 0)
  606.              length = 40, symbuf = (char *)malloc (length + 1);
  607.      
  608.            i = 0;
  609.            do
  610.              {
  611.                /* If buffer is full, make it bigger.        */
  612.                if (i == length)
  613.                  {
  614.                    length *= 2;
  615.                    symbuf = (char *)realloc (symbuf, length + 1);
  616.                  }
  617.                /* Add this character to the buffer.         */
  618.                symbuf[i++] = c;
  619.                /* Get another character.                    */
  620.                c = getchar ();
  621.              }
  622.            while (c != EOF && isalnum (c));
  623.      
  624.            ungetc (c, stdin);
  625.            symbuf[i] = '\0';
  626.      
  627.            s = getsym (symbuf);
  628.            if (s == 0)
  629.              s = putsym (symbuf, VAR);
  630.            yylval.tptr = s;
  631.            return s->type;
  632.          }
  633.      
  634.        /* Any other character is a token by itself.        */
  635.        return c;
  636.      }
  637.  
  638.    This program is both powerful and flexible. You may easily add new
  639. functions, and it is a simple job to modify this code to install
  640. predefined variables such as `pi' or `e' as well.
  641.  
  642. File: bison.info,  Node: Exercises,  Prev: Multi-function calc,  Up: Examples
  643.  
  644. Exercises
  645. =========
  646.  
  647.   1. Add some new functions from `math.h' to the initialization list.
  648.  
  649.   2. Add another array that contains constants and their values.  Then
  650.      modify `init_table' to add these constants to the symbol table. It
  651.      will be easiest to give the constants type `VAR'.
  652.  
  653.   3. Make the program report an error if the user refers to an
  654.      uninitialized variable in any way except to store a value in it.
  655.  
  656. File: bison.info,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  657.  
  658. Bison Grammar Files
  659. *******************
  660.  
  661.    Bison takes as input a context-free grammar specification and
  662. produces a C-language function that recognizes correct instances of the
  663. grammar.
  664.  
  665.    The Bison grammar input file conventionally has a name ending in
  666. `.y'.
  667.  
  668. * Menu:
  669.  
  670. * Grammar Outline::    Overall layout of the grammar file.
  671. * Symbols::            Terminal and nonterminal symbols.
  672. * Rules::              How to write grammar rules.
  673. * Recursion::          Writing recursive rules.
  674. * Semantics::          Semantic values and actions.
  675. * Declarations::       All kinds of Bison declarations are described here.
  676. * Multiple Parsers::   Putting more than one Bison parser in one program.
  677.  
  678. File: bison.info,  Node: Grammar Outline,  Next: Symbols,  Prev: Grammar File,  Up: Grammar File
  679.  
  680. Outline of a Bison Grammar
  681. ==========================
  682.  
  683.    A Bison grammar file has four main sections, shown here with the
  684. appropriate delimiters:
  685.  
  686.      %{
  687.      C DECLARATIONS
  688.      %}
  689.      
  690.      BISON DECLARATIONS
  691.      
  692.      %%
  693.      GRAMMAR RULES
  694.      %%
  695.      
  696.      ADDITIONAL C CODE
  697.  
  698.    Comments enclosed in `/* ... */' may appear in any of the sections.
  699.  
  700. * Menu:
  701.  
  702. * C Declarations::      Syntax and usage of the C declarations section.
  703. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  704. * Grammar Rules::       Syntax and usage of the grammar rules section.
  705. * C Code::              Syntax and usage of the additional C code section.
  706.  
  707. File: bison.info,  Node: C Declarations,  Next: Bison Declarations,  Prev: Grammar Outline,  Up: Grammar Outline
  708.  
  709. The C Declarations Section
  710. --------------------------
  711.  
  712.    The C DECLARATIONS section contains macro definitions and
  713. declarations of functions and variables that are used in the actions in
  714. the grammar rules.  These are copied to the beginning of the parser
  715. file so that they precede the definition of `yyparse'.  You can use
  716. `#include' to get the declarations from a header file.  If you don't
  717. need any C declarations, you may omit the `%{' and `%}' delimiters that
  718. bracket this section.
  719.  
  720. File: bison.info,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  721.  
  722. The Bison Declarations Section
  723. ------------------------------
  724.  
  725.    The BISON DECLARATIONS section contains declarations that define
  726. terminal and nonterminal symbols, specify precedence, and so on. In
  727. some simple grammars you may not need any declarations. *Note
  728. Declarations::.
  729.  
  730. File: bison.info,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  731.  
  732. The Grammar Rules Section
  733. -------------------------
  734.  
  735.    The "grammar rules" section contains one or more Bison grammar
  736. rules, and nothing else.  *Note Rules::.
  737.  
  738.    There must always be at least one grammar rule, and the first `%%'
  739. (which precedes the grammar rules) may never be omitted even if it is
  740. the first thing in the file.
  741.  
  742. File: bison.info,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  743.  
  744. The Additional C Code Section
  745. -----------------------------
  746.  
  747.    The ADDITIONAL C CODE section is copied verbatim to the end of the
  748. parser file, just as the C DECLARATIONS section is copied to the
  749. beginning.  This is the most convenient place to put anything that you
  750. want to have in the parser file but which need not come before the
  751. definition of `yyparse'.  For example, the definitions of `yylex' and
  752. `yyerror' often go here.  *Note Interface::.
  753.  
  754.    If the last section is empty, you may omit the `%%' that separates it
  755. from the grammar rules.
  756.  
  757.    The Bison parser itself contains many static variables whose names
  758. start with `yy' and many macros whose names start with `YY'.  It is a
  759. good idea to avoid using any such names (except those documented in this
  760. manual) in the additional C code section of the grammar file.
  761.  
  762. File: bison.info,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  763.  
  764. Symbols, Terminal and Nonterminal
  765. =================================
  766.  
  767.    "Symbols" in Bison grammars represent the grammatical classifications
  768. of the language.
  769.  
  770.    A "terminal symbol" (also known as a "token type") represents a
  771. class of syntactically equivalent tokens.  You use the symbol in grammar
  772. rules to mean that a token in that class is allowed.  The symbol is
  773. represented in the Bison parser by a numeric code, and the `yylex'
  774. function returns a token type code to indicate what kind of token has
  775. been read.  You don't need to know what the code value is; you can use
  776. the symbol to stand for it.
  777.  
  778.    A "nonterminal symbol" stands for a class of syntactically equivalent
  779. groupings.  The symbol name is used in writing grammar rules.  By
  780. convention, it should be all lower case.
  781.  
  782.    Symbol names can contain letters, digits (not at the beginning),
  783. underscores and periods.  Periods make sense only in nonterminals.
  784.  
  785.    There are two ways of writing terminal symbols in the grammar:
  786.  
  787.    * A "named token type" is written with an identifier, like an
  788.      identifier in C.  By convention, it should be all upper case.  Each
  789.      such name must be defined with a Bison declaration such as
  790.      `%token'.  *Note Token Decl::.
  791.  
  792.    * A "character token type" (or "literal token") is written in the
  793.      grammar using the same syntax used in C for character constants;
  794.      for example, `'+'' is a character token type.  A character token
  795.      type doesn't need to be declared unless you need to specify its
  796.      semantic value data type (*note Value Type::.), associativity, or
  797.      precedence (*note Precedence::.).
  798.  
  799.      By convention, a character token type is used only to represent a
  800.      token that consists of that particular character.  Thus, the token
  801.      type `'+'' is used to represent the character `+' as a token. 
  802.      Nothing enforces this convention, but if you depart from it, your
  803.      program will confuse other readers.
  804.  
  805.      All the usual escape sequences used in character literals in C can
  806.      be used in Bison as well, but you must not use the null character
  807.      as a character literal because its ASCII code, zero, is the code
  808.      `yylex' returns for end-of-input (*note Calling Convention::.).
  809.  
  810.    How you choose to write a terminal symbol has no effect on its
  811. grammatical meaning.  That depends only on where it appears in rules and
  812. on when the parser function returns that symbol.
  813.  
  814.    The value returned by `yylex' is always one of the terminal symbols
  815. (or 0 for end-of-input).  Whichever way you write the token type in the
  816. grammar rules, you write it the same way in the definition of `yylex'.
  817. The numeric code for a character token type is simply the ASCII code for
  818. the character, so `yylex' can use the identical character constant to
  819. generate the requisite code.  Each named token type becomes a C macro in
  820. the parser file, so `yylex' can use the name to stand for the code.
  821. (This is why periods don't make sense in terminal symbols.)  *Note
  822. Calling Convention::.
  823.  
  824.    If `yylex' is defined in a separate file, you need to arrange for the
  825. token-type macro definitions to be available there.  Use the `-d'
  826. option when you run Bison, so that it will write these macro definitions
  827. into a separate header file `NAME.tab.h' which you can include in the
  828. other source files that need it.  *Note Invocation::.
  829.  
  830.    The symbol `error' is a terminal symbol reserved for error recovery
  831. (*note Error Recovery::.); you shouldn't use it for any other purpose.
  832. In particular, `yylex' should never return this value.
  833.  
  834. File: bison.info,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  835.  
  836. Syntax of Grammar Rules
  837. =======================
  838.  
  839.    A Bison grammar rule has the following general form:
  840.  
  841.      RESULT: COMPONENTS...
  842.              ;
  843.  
  844. where RESULT is the nonterminal symbol that this rule describes and
  845. COMPONENTS are various terminal and nonterminal symbols that are put
  846. together by this rule (*note Symbols::.).
  847.  
  848.    For example,
  849.  
  850.      exp:      exp '+' exp
  851.              ;
  852.  
  853. says that two groupings of type `exp', with a `+' token in between, can
  854. be combined into a larger grouping of type `exp'.
  855.  
  856.    Whitespace in rules is significant only to separate symbols.  You
  857. can add extra whitespace as you wish.
  858.  
  859.    Scattered among the components can be ACTIONS that determine the
  860. semantics of the rule.  An action looks like this:
  861.  
  862.      {C STATEMENTS}
  863.  
  864. Usually there is only one action and it follows the components. *Note
  865. Actions::.
  866.  
  867.    Multiple rules for the same RESULT can be written separately or can
  868. be joined with the vertical-bar character `|' as follows:
  869.  
  870.      RESULT:   RULE1-COMPONENTS...
  871.              | RULE2-COMPONENTS...
  872.              ...
  873.              ;
  874.  
  875. They are still considered distinct rules even when joined in this way.
  876.  
  877.    If COMPONENTS in a rule is empty, it means that RESULT can match the
  878. empty string.  For example, here is how to define a comma-separated
  879. sequence of zero or more `exp' groupings:
  880.  
  881.      expseq:   /* empty */
  882.              | expseq1
  883.              ;
  884.      
  885.      expseq1:  exp
  886.              | expseq1 ',' exp
  887.              ;
  888.  
  889. It is customary to write a comment `/* empty */' in each rule with no
  890. components.
  891.  
  892. File: bison.info,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  893.  
  894. Recursive Rules
  895. ===============
  896.  
  897.    A rule is called "recursive" when its RESULT nonterminal appears
  898. also on its right hand side.  Nearly all Bison grammars need to use
  899. recursion, because that is the only way to define a sequence of any
  900. number of somethings.  Consider this recursive definition of a
  901. comma-separated sequence of one or more expressions:
  902.  
  903.      expseq1:  exp
  904.              | expseq1 ',' exp
  905.              ;
  906.  
  907. Since the recursive use of `expseq1' is the leftmost symbol in the
  908. right hand side, we call this "left recursion".  By contrast, here the
  909. same construct is defined using "right recursion":
  910.  
  911.      expseq1:  exp
  912.              | exp ',' expseq1
  913.              ;
  914.  
  915. Any kind of sequence can be defined using either left recursion or
  916. right recursion, but you should always use left recursion, because it
  917. can parse a sequence of any number of elements with bounded stack
  918. space.  Right recursion uses up space on the Bison stack in proportion
  919. to the number of elements in the sequence, because all the elements
  920. must be shifted onto the stack before the rule can be applied even
  921. once.  *Note The Algorithm of the Bison Parser: Algorithm, for further
  922. explanation of this.
  923.  
  924.    "Indirect" or "mutual" recursion occurs when the result of the rule
  925. does not appear directly on its right hand side, but does appear in
  926. rules for other nonterminals which do appear on its right hand side.
  927.  
  928.    For example:
  929.  
  930.      expr:     primary
  931.              | primary '+' primary
  932.              ;
  933.      
  934.      primary:  constant
  935.              | '(' expr ')'
  936.              ;
  937.  
  938. defines two mutually-recursive nonterminals, since each refers to the
  939. other.
  940.  
  941. File: bison.info,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  942.  
  943. Defining Language Semantics
  944. ===========================
  945.  
  946.    The grammar rules for a language determine only the syntax.  The
  947. semantics are determined by the semantic values associated with various
  948. tokens and groupings, and by the actions taken when various groupings
  949. are recognized.
  950.  
  951.    For example, the calculator calculates properly because the value
  952. associated with each expression is the proper number; it adds properly
  953. because the action for the grouping `X + Y' is to add the numbers
  954. associated with X and Y.
  955.  
  956. * Menu:
  957.  
  958. * Value Type::       Specifying one data type for all semantic values.
  959. * Multiple Types::   Specifying several alternative data types.
  960. * Actions::          An action is the semantic definition of a grammar rule.
  961. * Action Types::     Specifying data types for actions to operate on.
  962. * Mid-Rule Actions:: Most actions go at the end of a rule.
  963.                       This says when, why and how to use the exceptional
  964.                       action in the middle of a rule.
  965.  
  966. File: bison.info,  Node: Value Type,  Next: Multiple Types,  Prev: Semantics,  Up: Semantics
  967.  
  968. Data Types of Semantic Values
  969. -----------------------------
  970.  
  971.    In a simple program it may be sufficient to use the same data type
  972. for the semantic values of all language constructs.  This was true in
  973. the RPN and infix calculator examples (*note RPN Calc::.).
  974.  
  975.    Bison's default is to use type `int' for all semantic values.  To
  976. specify some other type, define `YYSTYPE' as a macro, like this:
  977.  
  978.      #define YYSTYPE double
  979.  
  980. This macro definition must go in the C declarations section of the
  981. grammar file (*note Grammar Outline::.).
  982.  
  983. File: bison.info,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  984.  
  985. More Than One Value Type
  986. ------------------------
  987.  
  988.    In most programs, you will need different data types for different
  989. kinds of tokens and groupings.  For example, a numeric constant may
  990. need type `int' or `long', while a string constant needs type `char *',
  991. and an identifier might need a pointer to an entry in the symbol table.
  992.  
  993.    To use more than one data type for semantic values in one parser,
  994. Bison requires you to do two things:
  995.  
  996.    * Specify the entire collection of possible data types, with the
  997.      `%union' Bison declaration (*note Union Decl::.).
  998.  
  999.    * Choose one of those types for each symbol (terminal or nonterminal)
  1000.      for which semantic values are used.  This is done for tokens with
  1001.      the `%token' Bison declaration (*note Token Decl::.) and for
  1002.      groupings with the `%type' Bison declaration (*note Type Decl::.).
  1003.  
  1004. File: bison.info,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  1005.  
  1006. Actions
  1007. -------
  1008.  
  1009.    An action accompanies a syntactic rule and contains C code to be
  1010. executed each time an instance of that rule is recognized.  The task of
  1011. most actions is to compute a semantic value for the grouping built by
  1012. the rule from the semantic values associated with tokens or smaller
  1013. groupings.
  1014.  
  1015.    An action consists of C statements surrounded by braces, much like a
  1016. compound statement in C.  It can be placed at any position in the rule;
  1017. it is executed at that position.  Most rules have just one action at
  1018. the end of the rule, following all the components.  Actions in the
  1019. middle of a rule are tricky and used only for special purposes (*note
  1020. Mid-Rule Actions::.).
  1021.  
  1022.    The C code in an action can refer to the semantic values of the
  1023. components matched by the rule with the construct `$N', which stands for
  1024. the value of the Nth component.  The semantic value for the grouping
  1025. being constructed is `$$'.  (Bison translates both of these constructs
  1026. into array element references when it copies the actions into the parser
  1027. file.)
  1028.  
  1029.    Here is a typical example:
  1030.  
  1031.      exp:    ...
  1032.              | exp '+' exp
  1033.                  { $$ = $1 + $3; }
  1034.  
  1035. This rule constructs an `exp' from two smaller `exp' groupings
  1036. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  1037. the semantic values of the two component `exp' groupings, which are the
  1038. first and third symbols on the right hand side of the rule. The sum is
  1039. stored into `$$' so that it becomes the semantic value of the
  1040. addition-expression just recognized by the rule.  If there were a
  1041. useful semantic value associated with the `+' token, it could be
  1042. referred to as `$2'.
  1043.  
  1044.    `$N' with N zero or negative is allowed for reference to tokens and
  1045. groupings on the stack *before* those that match the current rule. 
  1046. This is a very risky practice, and to use it reliably you must be
  1047. certain of the context in which the rule is applied.  Here is a case in
  1048. which you can use this reliably:
  1049.  
  1050.      foo:      expr bar '+' expr  { ... }
  1051.              | expr bar '-' expr  { ... }
  1052.              ;
  1053.      
  1054.      bar:      /* empty */
  1055.              { previous_expr = $0; }
  1056.              ;
  1057.  
  1058.    As long as `bar' is used only in the fashion shown here, `$0' always
  1059. refers to the `expr' which precedes `bar' in the definition of `foo'.
  1060.  
  1061. File: bison.info,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  1062.  
  1063. Data Types of Values in Actions
  1064. -------------------------------
  1065.  
  1066.    If you have chosen a single data type for semantic values, the `$$'
  1067. and `$N' constructs always have that data type.
  1068.  
  1069.    If you have used `%union' to specify a variety of data types, then
  1070. you must declare a choice among these types for each terminal or
  1071. nonterminal symbol that can have a semantic value.  Then each time you
  1072. use `$$' or `$N', its data type is determined by which symbol it refers
  1073. to in the rule.  In this example,
  1074.  
  1075.      exp:    ...
  1076.              | exp '+' exp
  1077.                  { $$ = $1 + $3; }
  1078.  
  1079. `$1' and `$3' refer to instances of `exp', so they all have the data
  1080. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  1081. would have the data type declared for the terminal symbol `'+'',
  1082. whatever that might be.
  1083.  
  1084.    Alternatively, you can specify the data type when you refer to the
  1085. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1086. reference.  For example, if you have defined types as shown here:
  1087.  
  1088.      %union {
  1089.        int itype;
  1090.        double dtype;
  1091.      }
  1092.  
  1093. then you can write `$<itype>1' to refer to the first subunit of the
  1094. rule as an integer, or `$<dtype>1' to refer to it as a double.
  1095.  
  1096. File: bison.info,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  1097.  
  1098. Actions in Mid-Rule
  1099. -------------------
  1100.  
  1101.    Occasionally it is useful to put an action in the middle of a rule.
  1102. These actions are written just like usual end-of-rule actions, but they
  1103. are executed before the parser even recognizes the following components.
  1104.  
  1105.    A mid-rule action may refer to the components preceding it using
  1106. `$N', but it may not refer to subsequent components because it is run
  1107. before they are parsed.
  1108.  
  1109.    The mid-rule action itself counts as one of the components of the
  1110. rule. This makes a difference when there is another action later in the
  1111. same rule (and usually there is another at the end): you have to count
  1112. the actions along with the symbols when working out which number N to
  1113. use in `$N'.
  1114.  
  1115.    The mid-rule action can also have a semantic value.  This can be set
  1116. within that action by an assignment to `$$', and can referred to by
  1117. actions later in the rule using `$N'.  Since there is no symbol to name
  1118. the action, there is no way to declare a data type for the value in
  1119. advance, so you must use the `$<...>' construct to specify a data type
  1120. each time you refer to this value.
  1121.  
  1122.    There is no way to set the value of the entire rule with a mid-rule
  1123. action, because assignments to `$$' do not have that effect.  The only
  1124. way to set the value for the entire rule is with an ordinary action at
  1125. the end of the rule.
  1126.  
  1127.    Here is an example from a hypothetical compiler, handling a `let'
  1128. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  1129. create a variable named VARIABLE temporarily for the duration of
  1130. STATEMENT.  To parse this construct, we must put VARIABLE into the
  1131. symbol table while STATEMENT is parsed, then remove it afterward.  Here
  1132. is how it is done:
  1133.  
  1134.      stmt:   LET '(' var ')'
  1135.                      { $<context>$ = push_context ();
  1136.                        declare_variable ($3); }
  1137.              stmt    { $$ = $6;
  1138.                        pop_context ($<context>5); }
  1139.  
  1140. As soon as `let (VARIABLE)' has been recognized, the first action is
  1141. run.  It saves a copy of the current semantic context (the list of
  1142. accessible variables) as its semantic value, using alternative
  1143. `context' in the data-type union.  Then it calls `declare_variable' to
  1144. add the new variable to that list.  Once the first action is finished,
  1145. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  1146. action is component number 5, so the `stmt' is component number 6.
  1147.  
  1148.    After the embedded statement is parsed, its semantic value becomes
  1149. the value of the entire `let'-statement.  Then the semantic value from
  1150. the earlier action is used to restore the prior list of variables.  This
  1151. removes the temporary `let'-variable from the list so that it won't
  1152. appear to exist while the rest of the program is parsed.
  1153.  
  1154.    Taking action before a rule is completely recognized often leads to
  1155. conflicts since the parser must commit to a parse in order to execute
  1156. the action.  For example, the following two rules, without mid-rule
  1157. actions, can coexist in a working parser because the parser can shift
  1158. the open-brace token and look at what follows before deciding whether
  1159. there is a declaration or not:
  1160.  
  1161.      compound: '{' declarations statements '}'
  1162.              | '{' statements '}'
  1163.              ;
  1164.  
  1165. But when we add a mid-rule action as follows, the rules become
  1166. nonfunctional:
  1167.  
  1168.      compound: { prepare_for_local_variables (); }
  1169.                '{' declarations statements '}'
  1170.              | '{' statements '}'
  1171.              ;
  1172.  
  1173. Now the parser is forced to decide whether to run the mid-rule action
  1174. when it has read no farther than the open-brace.  In other words, it
  1175. must commit to using one rule or the other, without sufficient
  1176. information to do it correctly.  (The open-brace token is what is called
  1177. the "look-ahead" token at this time, since the parser is still deciding
  1178. what to do about it.  *Note Look-Ahead::.)
  1179.  
  1180.    You might think that you could correct the problem by putting
  1181. identical actions into the two rules, like this:
  1182.  
  1183.      compound: { prepare_for_local_variables (); }
  1184.                '{' declarations statements '}'
  1185.              | { prepare_for_local_variables (); }
  1186.                '{' statements '}'
  1187.              ;
  1188.  
  1189. But this does not help, because Bison does not realize that the two
  1190. actions are identical.  (Bison never tries to understand the C code in
  1191. an action.)
  1192.  
  1193.    If the grammar is such that a declaration can be distinguished from a
  1194. statement by the first token (which is true in C), then one solution
  1195. which does work is to put the action after the open-brace, like this:
  1196.  
  1197.      compound: '{' { prepare_for_local_variables (); }
  1198.                declarations statements '}'
  1199.              | '{' statements '}'
  1200.              ;
  1201.  
  1202. Now the first token of the following declaration or statement, which
  1203. would in any case tell Bison which rule to use, can still do so.
  1204.  
  1205.    Another solution is to bury the action inside a nonterminal symbol
  1206. which serves as a subroutine:
  1207.  
  1208.      subroutine: /* empty */
  1209.                { prepare_for_local_variables (); }
  1210.              ;
  1211.      
  1212.      compound: subroutine
  1213.                '{' declarations statements '}'
  1214.              | subroutine
  1215.                '{' statements '}'
  1216.              ;
  1217.  
  1218. Now Bison can execute the action in the rule for `subroutine' without
  1219. deciding which rule for `compound' it will eventually use.  Note that
  1220. the action is now at the end of its rule.  Any mid-rule action can be
  1221. converted to an end-of-rule action in this way, and this is what Bison
  1222. actually does to implement mid-rule actions.
  1223.  
  1224. File: bison.info,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  1225.  
  1226. Bison Declarations
  1227. ==================
  1228.  
  1229.    The "Bison declarations" section of a Bison grammar defines the
  1230. symbols used in formulating the grammar and the data types of semantic
  1231. values. *Note Symbols::.
  1232.  
  1233.    All token type names (but not single-character literal tokens such as
  1234. `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  1235. declared if you need to specify which data type to use for the semantic
  1236. value (*note Multiple Types::.).
  1237.  
  1238.    The first rule in the file also specifies the start symbol, by
  1239. default. If you want some other symbol to be the start symbol, you must
  1240. declare it explicitly (*note Language and Grammar::.).
  1241.  
  1242. * Menu:
  1243.  
  1244. * Token Decl::       Declaring terminal symbols.
  1245. * Precedence Decl::  Declaring terminals with precedence and associativity.
  1246. * Union Decl::       Declaring the set of all semantic value types.
  1247. * Type Decl::        Declaring the choice of type for a nonterminal symbol.
  1248. * Expect Decl::      Suppressing warnings about shift/reduce conflicts.
  1249. * Start Decl::       Specifying the start symbol.
  1250. * Pure Decl::        Requesting a reentrant parser.
  1251. * Decl Summary::     Table of all Bison declarations.
  1252.  
  1253. File: bison.info,  Node: Token Decl,  Next: Precedence Decl,  Prev: Declarations,  Up: Declarations
  1254.  
  1255. Token Type Names
  1256. ----------------
  1257.  
  1258.    The basic way to declare a token type name (terminal symbol) is as
  1259. follows:
  1260.  
  1261.      %token NAME
  1262.  
  1263.    Bison will convert this into a `#define' directive in the parser, so
  1264. that the function `yylex' (if it is in this file) can use the name NAME
  1265. to stand for this token type's code.
  1266.  
  1267.    Alternatively you can use `%left', `%right', or `%nonassoc' instead
  1268. of `%token', if you wish to specify precedence. *Note Precedence Decl::.
  1269.  
  1270.    You can explicitly specify the numeric code for a token type by
  1271. appending an integer value in the field immediately following the token
  1272. name:
  1273.  
  1274.      %token NUM 300
  1275.  
  1276. It is generally best, however, to let Bison choose the numeric codes for
  1277. all token types.  Bison will automatically select codes that don't
  1278. conflict with each other or with ASCII characters.
  1279.  
  1280.    In the event that the stack type is a union, you must augment the
  1281. `%token' or other token declaration to include the data type
  1282. alternative delimited by angle-brackets (*note Multiple Types::.).
  1283.  
  1284.    For example:
  1285.  
  1286.      %union {              /* define stack type */
  1287.        double val;
  1288.        symrec *tptr;
  1289.      }
  1290.      %token <val> NUM      /* define token NUM and its type */
  1291.  
  1292. File: bison.info,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  1293.  
  1294. Operator Precedence
  1295. -------------------
  1296.  
  1297.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  1298. token and specify its precedence and associativity, all at once.  These
  1299. are called "precedence declarations". *Note Precedence::, for general
  1300. information on operator precedence.
  1301.  
  1302.    The syntax of a precedence declaration is the same as that of
  1303. `%token': either
  1304.  
  1305.      %left SYMBOLS...
  1306.  
  1307. or
  1308.  
  1309.      %left <TYPE> SYMBOLS...
  1310.  
  1311.    And indeed any of these declarations serves the purposes of `%token'.
  1312. But in addition, they specify the associativity and relative precedence
  1313. for all the SYMBOLS:
  1314.  
  1315.    * The associativity of an operator OP determines how repeated uses
  1316.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  1317.      X with Y first or by grouping Y with Z first.  `%left' specifies
  1318.      left-associativity (grouping X with Y first) and `%right'
  1319.      specifies right-associativity (grouping Y with Z first). 
  1320.      `%nonassoc' specifies no associativity, which means that `X OP Y
  1321.      OP Z' is considered a syntax error.
  1322.  
  1323.    * The precedence of an operator determines how it nests with other
  1324.      operators. All the tokens declared in a single precedence
  1325.      declaration have equal precedence and nest together according to
  1326.      their associativity. When two tokens declared in different
  1327.      precedence declarations associate, the one declared later has the
  1328.      higher precedence and is grouped first.
  1329.  
  1330. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  1331.  
  1332. The Collection of Value Types
  1333. -----------------------------
  1334.  
  1335.    The `%union' declaration specifies the entire collection of possible
  1336. data types for semantic values.  The keyword `%union' is followed by a
  1337. pair of braces containing the same thing that goes inside a `union' in
  1338. C.
  1339.  
  1340.    For example:
  1341.  
  1342.      %union {
  1343.        double val;
  1344.        symrec *tptr;
  1345.      }
  1346.  
  1347. This says that the two alternative types are `double' and `symrec *'. 
  1348. They are given names `val' and `tptr'; these names are used in the
  1349. `%token' and `%type' declarations to pick one of the types for a
  1350. terminal or nonterminal symbol (*note Type Decl::.).
  1351.  
  1352.    Note that, unlike making a `union' declaration in C, you do not write
  1353. a semicolon after the closing brace.
  1354.